package com.example.springsecuritydemo2.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springsecuritydemo2.common.R;
import com.example.springsecuritydemo2.domain.User;
import com.example.springsecuritydemo2.domain.vo.LoginUser;
import com.example.springsecuritydemo2.mapper.UserMapper;
import com.example.springsecuritydemo2.service.UserService;
import com.example.springsecuritydemo2.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(User user) {
        // 1、封装Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 2、进行校验
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 3、如果authentication 为空，说明认证失败
        if(authenticate == null){
            return "认证失败";
        }
        // 拿到放入的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 使用fastJson方法，把对象转成字符串
        String loginUserString = JSON.toJSONString(loginUser);
        // 4、生成jwt
        String jwt = JwtUtil.createJwt(loginUserString, null);

        String tokenKey = "token_" + jwt;
        stringRedisTemplate.opsForValue().set(tokenKey, jwt , JwtUtil.TTL/1000 , TimeUnit.SECONDS);

        return jwt;

    }
}
